<template>
  <el-container class="full">
    <el-header height="160px">
      <div style="display: flex;justify-content: space-between; width: 100%;">
        <div>

          <br/> <input id="uploadBtn" type="file" @change="loadExcel"/>&nbsp;&nbsp;

<!--          <el-button @click="exportdata">打印到控制台</el-button>-->

<!--          <el-button @click="exportlog">导出当前json</el-button>-->

          <el-button @click="downloadExcel">下载当前excel文件(无样式)</el-button>

          <br/><input v-model="subExcelUrl" style="width: 500px;  font-size: 16px;"/>
          <el-button @click="subExcelServer">生成当前excel文件提交到后台服务</el-button>

          <br/><input v-model="getExcelUrl" style="width: 500px;  font-size: 16px;"/>
          <el-button @click="getExcelServerUrl">指定excel下载路径渲染页面</el-button>
        </div>
        <div>
          列
          <el-input v-model="row" style="width: 100px;"></el-input>
          行
          <el-input v-model="column" style="width: 100px;"></el-input>
          <el-button @click="jian">剪切</el-button>
        </div>

      </div>
      <div class="m10">
        <el-radio-group v-model="radio1" size="large">
          <el-radio-button :label="item.name" @change="changeRadio(index)"
                           v-for="(item, index) in jsonData.sheets"/>
        </el-radio-group>
      </div>

    </el-header>
    <el-main>
      <div class="full" id="luckysheet"></div>
    </el-main>
  </el-container>
  <div v-show="isMaskShow" id="tip">Downloading</div>
</template>

<script setup>
//导入
import {ref, onMounted, reactive} from 'vue'
import {exportExcel, subExcelToUrl} from './export'
import LuckyExcel from 'luckyexcel'
import _ from "lodash"
//变量
const isMaskShow = ref(false)
const selected = ref('')
const radio1 = ref('')
const row = ref(5)
const column = ref(10)
const jsonData = ref({})
let sheetData = []
//----------- 自参数---
// let subExcelUrl = 'http://192.168.8.125:8064/zbgl/questionOrder/importQuestion';
// let getExcelUrl = 'http://192.168.8.125:8064/zbgl/questionOrder/exportQuestionExcel';
let subExcelUrl = 'http://localhost:8102/importExcel';
let getExcelUrl = 'http://localhost:8102/exportExcel';
let excelUrl = null;
//-----------------
let sheetList = reactive([])
//方法
const loadExcel = (evt) => {
  console.log(evt);
  const files = evt.target.files
  if (files == null || files.length == 0) {
    alert('No files wait for import')
    return
  }

  let name = files[0].name
  let suffixArr = name.split('.'),
      suffix = suffixArr[suffixArr.length - 1]
  if (suffix != 'xlsx') {
    alert('Currently only supports the import of xlsx files')
    return
  }
  LuckyExcel.transformExcelToLucky(files[0], function (exportJson, luckysheetfile) {
    if (exportJson.sheets == null || exportJson.sheets.length == 0) {
      alert('Failed to read the content of the excel file, currently does not support xls files!')
      return
    }
    sheetData = _.cloneDeep(exportJson.sheets)
    sheetList = sheetData.map(item => {
      return {
        name: item.name
      }
    })
    jsonData.value = exportJson
    createLuckysheet()

  })
}

const selectExcel = (evt) => {
  const value = selected.value
  const name = evt.target.options[evt.target.selectedIndex].innerText

  if (value == '') {
    return
  }
  isMaskShow.value = true

  LuckyExcel.transformExcelToLuckyByUrl(value, name, (exportJson, luckysheetfile) => {
    if (exportJson.sheets == null || exportJson.sheets.length == 0) {
      alert('Failed to read the content of the excel file, currently does not support xls files!')
      return
    }
    console.log('exportJson', exportJson)
    jsonData.value = exportJson

    isMaskShow.value = false
    window.luckysheet.destroy()

    window.luckysheet.create({
      container: 'luckysheet', //luckysheet is the container id
      showinfobar: false,
      data: [...exportJson.sheets[0]],
      title: exportJson.info.name,
      userInfo: exportJson.info.name.creator
    })
    createLuckysheet()
  })
}

function createLuckysheet() {
  let data = sheetData[0]
  radio1.value = data.name
  console.log(data);
  createdata(data)

}

// 创建单sheet数据
function createdata(data, config = {}) {
  window.luckysheet.destroy()
  window.luckysheet.create({
    container: 'luckysheet', //luckysheet is the container id
    showinfobar: false,
    showtoolbar: false,
    sheetFormulaBar: false,
    showsheetbar: false,
    showstatisticBar: false,
    userInfo: false,
    enableAddRow: false,
    allowEdit: true,
    showsheetbarConfig: {},
    data: [data],
    title: radio1.value,
    config: config,
    userInfo: radio1.value,
    hook: {
      cellMousedown: (me, config) => {
        console.log(me, config);
        row.value = config.c + 1
        column.value = config.r + 1
      }
    }
  })
}

// Luckysheet 配置
function cearteLuckysheet(data) {
  let list = []
  list[0] = {
    config: data.config,
    data: data.data
  }
  window.luckysheet.create({
    container: 'luckysheet', //luckysheet is the container id
    showinfobar: false,
    showtoolbar: false,
    sheetFormulaBar: false,
    showsheetbar: false,
    showstatisticBar: false,
    userInfo: false,
    enableAddRow: false,
    allowEdit: true,
    showsheetbarConfig: {},
    lang: 'zh',
    allowCopy: false, //是否允许拷贝
    data: list,
    title: '',
    hook: {
      cellMousedown: (me, config) => {
        console.log(me, config);
        row.value = config.c + 1
        column.value = config.r + 1
      }
    }
  })
  window.luckysheet.setRangeShow('A100', {show: false})
}

function changeRadio(index) {
  console.log(index);
  createdata(sheetData[index])
}

const downloadExcel = () => {
  exportExcel(luckysheet.getAllSheets(), '下载')
}

const subExcelServer = () => {
  subExcelToUrl(luckysheet.getAllSheets(), subExcelUrl, '问题清单模板.xlsx');
}

async function getExcelServerUrl() {
  try {
    // Fetch the data asynchronously
    const response = await fetch(getExcelUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/octet-stream',
      },
    });
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    await new Promise(resolve => setTimeout(resolve, 3000));
    LuckyExcel.transformExcelToLucky(response.blob(), function (exportJson, luckysheetfile) {
      if (exportJson.sheets == null || exportJson.sheets.length == 0) {
        alert('Failed to read the content of the excel file, currently does not support xls files!')
        return
      }
      sheetData = _.cloneDeep(exportJson.sheets)
      sheetList = sheetData.map(item => {
        return {
          name: item.name
        }
      })
      jsonData.value = exportJson
      createLuckysheet()
    })
  } catch (error) {
    console.error('Error fetching Excel file:', error);
  }
}

function exportdata() {
  console.log(luckysheet.getAllSheets());
}

function exportlog() {
  jsonDownload(JSON.stringify(luckysheet.getAllSheets()))
  // download("http://127.0.0.1:8000/file/1.txt","1.txt")
}

function jsonDownload(stringData) {
  // dada 表示要转换的字符串数据，type 表示要转换的数据格式
  const blob = new Blob([stringData], {
    type: 'application/json'
  })
  // 根据 blob生成 url链接
  const objectURL = URL.createObjectURL(blob)

  // 创建一个 a 标签Tag
  const aTag = document.createElement('a')
  // 设置文件的下载地址
  aTag.href = objectURL
  // 设置保存后的文件名称
  aTag.download = radio1.value + ".json";
  // 给 a 标签添加点击事件
  aTag.click()
  // 释放一个之前已经存在的、通过调用 URL.createObjectURL() 创建的 URL 对象。
  // 当你结束使用某个 URL 对象之后，应该通过调用这个方法来让浏览器知道不用在内存中继续保留对这个文件的引用了。
  URL.revokeObjectURL(objectURL)
}

function jian() {

  let data = _.cloneDeep(luckysheet.getAllSheets()[0].data)
  console.log(data);
  let list = []
  for (let index = 0; index < column.value; index++) {
    if (!list[index]) {
      list[index] = []
    }
    for (let n = 0; n < row.value; n++) {
      list[index][n] = data[index][n]
    }
  }
  cearteLuckysheet({
    data: list,
    config: luckysheet.getAllSheets()[0].config
  })

}

// !!! create luckysheet after mounted
onMounted(() => {

  cearteLuckysheet([], {})

})

function download(url, name) {
  fetch(url).then((res) => {
    res.blob().then((blob) => {
      const url = window.URL.createObjectURL(blob)
      // end
      const a = document.createElement('a')
      a.href = url
      a.download = name
      a.rel = "noopener noreferrer";
      a.click()
      window.URL.revokeObjectURL(url)
    })
  })
}

</script>

<style scoped>
.m10 {
  margin-top: 10px;
}
</style>
